﻿using System;
using System.Web;
using System.Web.ModelBinding;

namespace Morus.Presentation
{
    public class HttpPostedFileBaseModelBinder : IModelBinder
    {
        internal static HttpPostedFileBase ChooseFileOrNull(HttpPostedFileBase rawFile)
        {
            if (rawFile == null)
            {
                return null;
            }
            if (rawFile.ContentLength == 0 && string.IsNullOrEmpty(rawFile.FileName))
            {
                return null;
            }
            return rawFile;
        }

        public bool BindModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext)
        {
            Check.Argument.IsNotNull(modelBindingExecutionContext, "modelBindingExecutionContext");
            Check.Argument.IsNotNull(bindingContext, "bindingContext");

            ValueProviderResult value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (value == null)
            {
                return false;
            }

            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);

            return true;
        }
    }
}
